<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Carbon\Carbon;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\View\View;

class PasswordController extends Controller
{
    use ValidatesRequests;

    public function repasswordEmailWeb():View
    {
        return view('password.repassword_email_web');
    }

    public function repasswordSendEmail(Request $request)
    {
         $this->validate($request,[
             'email'=>['required','email',Rule::exists('users')]
         ]);
         $email=$request->email;
         $token=hash_hmac('sha256',Str::random(32),config('app.key'));
         DB::table('password_resets')->updateOrInsert(
             ['email'=>$email],
             [
                'email'=>$email,
                'token'=>Hash::make($token),
                'created_at'=>new Carbon

             ]);

        // 生成重置密码链接
        $resetUrl = route('repassword.url', ['token' => $token]);

        Mail::send('emails.repassword_link',compact('resetUrl'), function ($message) use ($email) {
             $message->to($email)->subject('重置密码');
         });
        session()->flash('success','重置密码邮件发送成功');
        return redirect()->back();
    }

    public function repasswordUrl(Request $request)
    {
        $token = $request->route()->parameter('token');
        return view('emails.repassword_web',compact('token'));
    }

    public function passwordReset(Request $request)
    {
        $this->validate($request,[
           'token'=>['required'],
           'email'=>['required','email',Rule::exists('users')],
           'password'=>['required','min:6','confirmed']
        ]);

        $email = $request->email;
        $token = $request->token;
        $user = User::where('email',$email)->first();

        $res = (array)DB::table('password_resets')->where('email',$email)->first();
        if($res){
           //验证token的时效性
            if(Carbon::parse($res['created_at'])->addSeconds(60*10)->isPast()){
                session()->flash('warning','链接超时，请重新操作');
                return redirect()->back();
            }
            if(!Hash::check($token,$res['token'])){
                session()->flash('danger','失败,异常操作');
                return redirect()->back();
            }
            $user->update([
                'password'=>bcrypt($request->password)
            ]);
            session()->flash('success','密码重置成功');
            return redirect()->route('users.show',$user);
        }
        session()->flash('danger','未知错误');
        return redirect()->back();
    }
}
